//
//  DetailViewController.m
//  MyBlog
//
//  Created by NCS on 16/12/19.
//  Copyright © 2016年 YSL. All rights reserved.
//

#import "DetailViewController.h"
#import "DetailHeaderTableViewCell.h"
#import "CommentCell.h"
#import "DetailCellModel.h"
#import "ResponseViewController.h"

static NSString *CollectionViewCellIdentifier = @"homeCellCollectionCell";
CGFloat tabButtonWidth = 80.0;
CGFloat tabButtonHeight = 38.0;
CGFloat tabButtonGap = 10.0;

static long currentType = 1001;
static CGPoint forwardCurrentOffset;
static CGPoint commentCurrentOffset;
static CGPoint likeCurrentOffset;

static CGFloat sectionOneY = 0.0;

@interface DetailViewController ()

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Hide tabbar
    self.tabBarController.tabBar.hidden = YES;
    
    NSLog(@"Detail : %@", self.modal.name);

    // 去掉ScrollView顶部和底部预留的空白，（ > iOS 7.0 ）
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.detailTableView.delegate = self;
    self.detailTableView.dataSource = self;
    
    self.forwardHeights = [[NSMutableDictionary alloc] init];
    self.commentHeights = [[NSMutableDictionary alloc] init];
    self.likeHeights = [[NSMutableDictionary alloc] init];
    
    self.forwardList = [[NSMutableArray alloc] init];
    self.commentList = [[NSMutableArray alloc] init];
    self.likeList = [[NSMutableArray alloc] init];
    
    // Init data
    [self initData];
    
    forwardCurrentOffset = CGPointMake(0.0f, 0.0f);
    commentCurrentOffset = CGPointMake(0.0f, 0.0f);
    likeCurrentOffset = CGPointMake(0.0f, 0.0f);
    
    self.detailList = [[NSMutableArray alloc] initWithArray:self.forwardList];
    
//    UINib *headNib = [UINib nibWithNibName:@"DetailHeaderCell" bundle: [NSBundle mainBundle]];
    UINib *headNib = [UINib nibWithNibName:@"DetailHeaderTableViewCell" bundle: [NSBundle mainBundle]];
    [self.detailTableView registerNib:headNib forCellReuseIdentifier:@"DetailHeaderCell"];
    
    UINib *nib = [UINib nibWithNibName:@"CommentCell" bundle: [NSBundle mainBundle]];
    [self.detailTableView registerNib:nib forCellReuseIdentifier:@"DetailCommentCell"];
    
}

- (void)initData {
    // Forward data
    self.forwardList = [[NSMutableArray alloc] init];
    NSString *forwardPath = [[NSBundle mainBundle] pathForResource:@"ForwardData" ofType:@"plist"];
    NSMutableArray *tempForward = [[NSMutableArray alloc] initWithArray:[[NSArray alloc] initWithContentsOfFile:forwardPath]];
    
    for (NSDictionary *dic in tempForward) {
        DetailCellModel *model = [[DetailCellModel alloc] initWithData:dic];
        [self.forwardList addObject:model];
    }
    
    // Comment data
    NSString *commentPath = [[NSBundle mainBundle] pathForResource:@"CommentData" ofType:@"plist"];
    NSMutableArray *tempComment = [[NSMutableArray alloc] initWithArray:[[NSArray alloc] initWithContentsOfFile:commentPath]];
    
    for (NSDictionary *dic in tempComment) {
        DetailCellModel *model = [[DetailCellModel alloc] initWithData:dic];
        [self.commentList addObject:model];
    }
    
    // Like data
    NSString *likePath = [[NSBundle mainBundle] pathForResource:@"LikeData" ofType:@"plist"];
    NSMutableArray *tempLike = [[NSMutableArray alloc] initWithArray:[[NSArray alloc] initWithContentsOfFile:likePath]];
    
    for (NSDictionary *dic in tempLike) {
        DetailCellModel *model = [[DetailCellModel alloc] initWithData:dic];
        [self.likeList addObject:model];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self.detailTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)forward:(UIButton *)sender {
    
    ResponseViewController *vc = [[NSBundle mainBundle] loadNibNamed:@"ResponseViewController" owner:nil options:nil ].lastObject;
    
    [self presentViewController:vc animated:YES completion:^{
        
    }];

}

- (IBAction)comment:(UIButton *)sender {
}

- (IBAction)like:(UIButton *)sender {
}

// Tableview Section buttons
- (void)sectionClick:(UIButton *)sender {
    
    NSArray<UITableViewCell *> *cells = [[NSMutableArray alloc] init];
    cells = [self.detailTableView visibleCells];
    
    NSMutableArray *cellIndexPathes = [[NSMutableArray alloc] init];
    for (UITableViewCell *cell in cells) {
        NSIndexPath *index = [self.detailTableView indexPathForCell:cell];
        if (index.section == 0) {
            continue;
        }
        [cellIndexPathes addObject:index];
//        [self keepTableviewContentOffSetCell:cell];
    }
    
    if (currentType == sender.tag) {
       
        [self.detailTableView reloadRowsAtIndexPaths:cellIndexPathes withRowAnimation:UITableViewRowAnimationAutomatic];
        return;
    }
    
    currentType = sender.tag;
    
    UIButton *forwardBtn = (UIButton *)[self.view viewWithTag:1001];
    UIButton *commentBtn = (UIButton *)[self.view viewWithTag:1002];
    UIButton *likeBtn = (UIButton *)[self.view viewWithTag:1003];
    
    if (sender.tag == 1001) {
        
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            UIView *lineView = (UIView *)[self.view viewWithTag:1000];
            [lineView setFrame:CGRectMake(0, tabButtonHeight, tabButtonWidth, 2)];
            
            // Reset list data in section
            self.detailList = self.forwardList;
            
        } completion:^(BOOL finished) {
            
            forwardBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
            commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            
        }];
        
        NSLog(@"----Forward");
    } else if (sender.tag == 1002) {
        
        
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            UIView *lineView = (UIView *)[self.view viewWithTag:1000];
            [lineView setFrame:CGRectMake(tabButtonWidth + tabButtonGap, tabButtonHeight, tabButtonWidth, 2)];
            
            // Reset list data in section
            self.detailList = self.commentList;
            
        } completion:^(BOOL finished) {
            
            forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            commentBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
            likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            
        }];
        NSLog(@"----Comment");
    } else if (sender.tag == 1003) {
        
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            UIView *lineView = (UIView *)[self.view viewWithTag:1000];
            [lineView setFrame:CGRectMake(DScreenWidth - tabButtonWidth, tabButtonHeight, tabButtonWidth, 2)];
            
            // Reset list data in section
            self.detailList = self.likeList;
            
        } completion:^(BOOL finished) {
            
            forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            likeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
            
        }];
        NSLog(@"----Like");
    }
    
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
//    [self.detailTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
//    [UIView performWithoutAnimation:^{
//    [self.detailTableView reloadRowsAtIndexPaths:cellIndexPathes withRowAnimation:UITableViewRowAnimationNone];
    
    [self.detailTableView reloadData];
    
    
        // Scroll to pointed position
        CGPoint currentOffset = currentType == 1001 ? forwardCurrentOffset : currentType == 1002 ? commentCurrentOffset : likeCurrentOffset;
        [self.detailTableView setContentOffset:currentOffset];
        NSLog(@"click -- current offset : %f", currentOffset.y);
        
//    }];
    
//    [self.detailTableView layoutIfNeeded];
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   [self calculateOffsetAfterEndDeceleratingOrDragging:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self calculateOffsetAfterEndDeceleratingOrDragging:scrollView];
}

// Calculate offset after the scrollView end decelerating or dragging
- (void)calculateOffsetAfterEndDeceleratingOrDragging:(UIScrollView *)scrollView {
    NSLog(@"===type : %ld -- sectionOneY : %f -- scrollViewDidEndDecelerating : %f", currentType, sectionOneY, scrollView.contentOffset.y);
    NSLog(@"===scrollView conntent frame : %f", scrollView.contentSize.height);
    if (scrollView.contentOffset.y <= sectionOneY) {
        forwardCurrentOffset.y = scrollView.contentOffset.y >= 0 ? scrollView.contentOffset.y : 0;
        commentCurrentOffset.y = scrollView.contentOffset.y >= 0 ? scrollView.contentOffset.y : 0;
        likeCurrentOffset.y = scrollView.contentOffset.y >= 0 ? scrollView.contentOffset.y : 0;
        
        return;
    }
    
    if (currentType == 1001) {
        forwardCurrentOffset.y = scrollView.contentOffset.y;
        commentCurrentOffset.y = commentCurrentOffset.y <= sectionOneY? sectionOneY : commentCurrentOffset.y;
        likeCurrentOffset.y = likeCurrentOffset.y <= sectionOneY? sectionOneY : likeCurrentOffset.y;
    } else if (currentType == 1002) {
        commentCurrentOffset.y = scrollView.contentOffset.y;
        forwardCurrentOffset.y = forwardCurrentOffset.y <= sectionOneY? sectionOneY : forwardCurrentOffset.y;
        likeCurrentOffset.y = likeCurrentOffset.y <= sectionOneY? sectionOneY : likeCurrentOffset.y;
    } else if (currentType == 1003) {
        likeCurrentOffset.y = scrollView.contentOffset.y;
        commentCurrentOffset.y = commentCurrentOffset.y <= sectionOneY? sectionOneY : commentCurrentOffset.y;
        forwardCurrentOffset.y = forwardCurrentOffset.y <= sectionOneY? sectionOneY : forwardCurrentOffset.y;
    }
}

- (void)selectSection:(long)type {
    UIView *lineView = (UIView *)[self.view viewWithTag:1000];
    
    UIButton *forwardBtn = (UIButton *)[self.view viewWithTag:1001];
    UIButton *commentBtn = (UIButton *)[self.view viewWithTag:1002];
    UIButton *likeBtn = (UIButton *)[self.view viewWithTag:1003];
    
    if (type == 1001) {
        
        forwardBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(0, tabButtonHeight, tabButtonWidth, 2)];
    } else if (type == 1002) {
        
        forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(tabButtonWidth + tabButtonGap, tabButtonHeight, tabButtonWidth, 2)];
    } else if (type == 1003) {
        
        forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(DScreenWidth - tabButtonWidth, tabButtonHeight, tabButtonWidth, 2)];
    }
}


//-----------------------------------TableView Start----------------------------------------------
#pragma mark -- TableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }
    
    return [self.detailList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        DetailHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailHeaderCell" forIndexPath:indexPath];
        
        cell.modal = self.modal;
        
        cell.avatar.image = [UIImage imageNamed:self.modal.avatar];
        cell.name.text = self.modal.name;
        cell.time.text = self.modal.time;
        cell.device.text = self.modal.device;
        cell.content.text = self.modal.content;
        
//        cell.content.layer.borderColor = [[UIColor redColor] CGColor];
//        cell.content.layer.borderWidth = 1;
        
        [cell setCellData:self.modal];
        
        [cell.images reloadData];
        
        // Can not be selected
//        cell.userInteractionEnabled = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // Get the first section's height
//        CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
//        sectionOneY = size.height + 1.0f; // Add 1.0f for separator height
        
        sectionOneY = [cell getCellHeight];
        
        return cell;
    }
    
    DetailCellModel *model = self.detailList[indexPath.row];
    
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCommentCell" forIndexPath:indexPath];
    
    [cell setData:model];
    
    NSString* key = [NSString stringWithFormat:@"%ld",indexPath.row];
    NSNumber *height;
    if (currentType == 1001) {
        
        height = self.commentHeights[key];
        if (height == nil) {
            height = @(cell.cellHeight);
            [self.forwardHeights setValue:height forKey:key];
        }
        
    } else if (currentType == 1002) {
        
        height = self.commentHeights[key];
        if (height == nil) {
            height = @(cell.cellHeight);
            [self.commentHeights setValue:height forKey:key];
        }
    } else if (currentType == 1003) {
        
        height = self.likeHeights[key];
        if (height == nil) {
            height = @(cell.cellHeight);
            [self.likeHeights setValue:height forKey:key];
        }
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return 40;
}

//- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
//    if (section == 1) {
//        [self selectSection:currentType];
//    }
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return nil;
    }
    
    // Config section header
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    headView.backgroundColor = [UIColor whiteColor];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, tabButtonHeight, tabButtonWidth, 2)];
    lineView.backgroundColor = [UIColor orangeColor];
    lineView.tag = 1000;
    
    UIButton *forwardBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, tabButtonWidth, tabButtonHeight)];
    [forwardBtn setTitle:@"Forward" forState:UIControlStateNormal];
    [forwardBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    forwardBtn.tag = 1001;
    
    UIButton *commentBtn = [[UIButton alloc] initWithFrame:CGRectMake(tabButtonWidth + tabButtonGap, 0, tabButtonWidth, tabButtonHeight)];
    [commentBtn setTitle:@"Comment" forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    commentBtn.tag = 1002;
    
    UIButton *likeBtn = [[UIButton alloc] initWithFrame:CGRectMake(DScreenWidth - tabButtonWidth, 0, tabButtonWidth, tabButtonHeight)];
    [likeBtn setTitle:@"Like" forState:UIControlStateNormal];
    [likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    likeBtn.tag = 1003;
    
    if (currentType == 1001) {
        
        forwardBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(0, tabButtonHeight, tabButtonWidth, 2)];
    } else if (currentType == 1002) {
        
        forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(tabButtonWidth + tabButtonGap, tabButtonHeight, tabButtonWidth, 2)];
    } else if (currentType == 1003) {
        
        forwardBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        likeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        
        [lineView setFrame:CGRectMake(DScreenWidth - tabButtonWidth, tabButtonHeight, tabButtonWidth, 2)];
    }
    
    [forwardBtn addTarget:self action:@selector(sectionClick:) forControlEvents:UIControlEventTouchUpInside];
    [commentBtn addTarget:self action:@selector(sectionClick:) forControlEvents:UIControlEventTouchUpInside];
    [likeBtn addTarget:self action:@selector(sectionClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [headView addSubview:forwardBtn];
    [headView addSubview:commentBtn];
    [headView addSubview:likeBtn];
    
    [headView addSubview:lineView];
    
    return headView;
}

#pragma mark -- TableView Delegate
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (sectionOneY > 0 && indexPath.section == 0) {
//        return sectionOneY;
//    }
//    
////    NSString* key = [NSString stringWithFormat:@"%ld",indexPath.row];
////    NSNumber* height = [[NSNumber alloc] init];
////    
////    if (currentType == 1001) {
////        
////        height = self.forwardHeights[key];
////        
////    } else if (currentType == 1002) {
////        
////        height = self.commentHeights[key];
////        
////    } else if (currentType == 1003) {
////        
////        height = self.likeHeights[key];
////        
////    }
////    
////    if (height == nil) {
////        height = @(43);
////    }
////    
////    return height.floatValue;
//    
//    self.detailTableView.estimatedRowHeight = 43;
//    self.detailTableView.rowHeight = UITableViewAutomaticDimension;
//    return self.detailTableView.rowHeight;
//    
//    //    return MAXFLOAT;
//}

//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (sectionOneY > 0 && indexPath.section == 0) {
//        self.detailTableView.estimatedRowHeight = 43;
//        self.detailTableView.rowHeight = UITableViewAutomaticDimension;
//        
//        
//    }
//   return self.detailTableView.rowHeight;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (sectionOneY > 0 && indexPath.section == 0) {
//        self.detailTableView.estimatedRowHeight = 43;
//        self.detailTableView.rowHeight = UITableViewAutomaticDimension;
//        return self.detailTableView.rowHeight;
        return sectionOneY;
    }
    
    NSString* key = [NSString stringWithFormat:@"%ld",indexPath.row];
    NSNumber* height;
    DetailCellModel *model;
    
    if (currentType == 1001) {
        
        height = self.forwardHeights[key];
        if (height == nil) {
            
            model = self.forwardList[indexPath.row];
            height = @(model.cellHeight);
            [self.forwardHeights setValue:height forKey:key];
        }

    } else if (currentType == 1002) {
        
        height = self.commentHeights[key];
        if (height == nil) {
            model = self.commentList[indexPath.row];
            height = @(model.cellHeight);
            [self.commentHeights setValue:height forKey:key];
        }
    } else if (currentType == 1003) {
        
        height = self.likeHeights[key];
        if (height == nil) {
            model = self.likeList[indexPath.row];
            height = @(model.cellHeight);
            [self.likeHeights setValue:height forKey:key];
        }
    }
    
//    NSLog(@"index : %@ -- height = %f", indexPath, [height floatValue]);
    return [height floatValue];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Click : %ld - %ld", indexPath.section, indexPath.row);
    
    if (indexPath.section == 0) {
        return;
    }
    
    CommentCell *cell = [self.detailTableView cellForRowAtIndexPath:indexPath];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:cell.content.text preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Reply" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        ResponseViewController *vc = [[NSBundle mainBundle] loadNibNamed:@"ResponseViewController" owner:nil options:nil ].lastObject;
        
        [self presentViewController:vc animated:YES completion:^{
            
        }];
        
        NSLog(@"Reply");
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Forward" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"Forward");
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Copy" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"Copy");
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Report" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"Report");
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"Cancel");
        
    }]];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


//-----------------------------------TableView End----------------------------------------------

@end
